/**
 * 全局异常拦截
 */
package com.thermofisher.utils;

import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.naming.AuthenticationException;
import javax.servlet.http.HttpServletRequest;

/**
 * @author bairuihua
 * 2019/11/25
 */
@RestControllerAdvice
public class GlobalDefultExceptionHandler
{

    @ExceptionHandler(value = JSONException.class)
    public ResponseEntity<Result> handelJSONException(HttpServletRequest request, Exception e)
    {
        Result result = new Result();
        result.setCode("600");
        result.setMsg("JSON格式错误");
        ResponseEntity<Result> responseEntity = new ResponseEntity<Result>(result,
                                                                           HttpStatus.NOT_FOUND);
        return responseEntity;
    }

    @ExceptionHandler(value = AuthenticationException.class)
    public ResponseEntity<Result> handlerAuthentication(HttpServletRequest req,
                                                        AuthenticationException e)
    {
        Result result = new Result();
        result.setCode(HttpStatus.UNAUTHORIZED.toString());
        result.setMsg(e.getMessage());
        ResponseEntity<Result> responseEntity = new ResponseEntity<Result>(result,
                                                                           HttpStatus.UNAUTHORIZED);
        return responseEntity;
    }

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<Result> handleException(HttpServletRequest request, Exception e)
    {
        Result result = new Result();
        result.setCode(HttpStatus.INTERNAL_SERVER_ERROR.toString());
        result.setMsg(e.getMessage());
        ResponseEntity<Result> responseEntity = new ResponseEntity<Result>(result,
                                                                           HttpStatus.INTERNAL_SERVER_ERROR);
        return responseEntity;
    }

}
